
/*
  *		Heartbeat 
  *
  */
#include <heartbeat.h>

#define INFO_LENGTH 2*MAX_LINE_LENGTH+MAX_HOSTNAME_LENGTH+64+3*sizeof(int)+2*sizeof(unsigned long)

void rp_rindexd_heartbeat(int fd, short event, void *arg)
{
	static char fname[] = "rp_rindexd_heartbeat";
	static char msg[] = "fatal message";
	Err err;
	static int clifd;
	static struct sockaddr_in cliaddr;
	static socklen_t clilength;
	struct event *ev;
	FLOG_IN(fname);

	/*	accept the tcp connection   */
	memset(&cliaddr, 0, sizeof(struct sockaddr_in));
	clilength = 0;
	if (!(clifd = rp_comm_accept(fd, &cliaddr, &clilength)))	
	{
		rp_log(LOG_ERROR, fname, "No heartbeat connection is setup.");
		return;
	}
	
	/*	Install event	 */    
	ev = malloc(sizeof(struct event));    
	event_set(ev, clifd, EV_READ|EV_PERSIST, rp_rindexd_heartbeat_get, NULL);    
	event_add(ev, NULL);

	FLOG_OUT(fname);
}

void rp_rindexd_heartbeat_get(int fd, short event, void *arg)
{
	static char fname[] = "rp_rindexd_heartbeat_get";
	static char msg[] = "fatal message";
	Err err;
	static Info info;
	int size;
	void *buf;
	FLOG_IN(fname);


	/*	recv the heartbeat information   */
	rp_comm_recv(fd, &size, sizeof(int));
	buf = (void*)malloc(size);
	if (rp_comm_recv(fd, buf, size) < size)
	{
		rp_log(LOG_WARNING, fname, "Cannot receive heartbeat information from the host %s");	// TODO: cliaddr
		return;
	}
	
	memset(&info, 0, sizeof(Info));
	memcpy(&info, buf, INFO_LENGTH);
	
	err = rp_infoq_push(&global.infoq, &info);
	err = rp_sem_post(&global.sem_manager);	

	FLOG_OUT(fname);
}

